// pages/course/course.js
import {
  BASE_URL
} from '../../../http/config';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mainNews: [], // 咨询师的主要信息
    item: [], // 咨询师的擅长领域   consultExpertise/selectConsultExpert/{id}
    list: [], // 总的擅长领域列表  
    result: [], // 匹配后的擅长领域
    evaluate: [], // 咨询师的评价
    id: '',
    isModalVisible: false, // 控制弹出层的显示与隐藏
    inputValue: '', // 输入框的内容
    isModalVisibleAsk: false, // 控制弹出层的显示与隐藏
    inputValueAsk: '', // 输入框的内容
    charges: [], // 咨询师收费标准
    message: [], // 获取咨询师 留言
    // img: BASE_URL,
    img:'',
    range: ['1', '2', '3', '4', '5'], // 下拉框的选项
    selectedValue: '5', // 当前选择的值
    isOrder: false, // 是否通过订单进入
    imgSrc: '' // 先设为空
  },
  showImage() {
    this.setData({
      showMask: true
    });
  },

  // 关闭遮罩
  hideImage() {
    this.setData({
      showMask: false
    });
  },

  // 空函数，阻止事件冒泡
  noop() {},
  fetchCourseDetail: function (id) {
    if (!id) {
      wx.showToast({
        title: '无ID',
        icon: 'none'
      });
      return;
    }
    const _this = this;
    wx.request({
      url: `${BASE_URL}/consult/${id}`,
      success(res) {
        console.log(res);
        _this.setData({
          mainNews: res.data.data,
        })
      }
    })
  },

  // 获取咨询师擅长领域 需要配合擅长领域管理使用 
  getConsultExpertis: function (id) {
    // console.log("哈哈哈哈哈哈");
    wx.request({
      url: `${BASE_URL}/consultExpertise/selectConsultExpert/${id}`,
      success: (res) => {
        console.log("这个咨询师擅长的领域id", res);
        this.setData({
          item: res.data.data.exceptList
        });
        // console.log("item", this.data.item);
        const result = this.data.list
          .filter(item => this.data.item.includes(item.id))
          .map(item => item.expertise);
        this.setData({
          result: result
        })
        console.log(this.data.result);
      }

    });
  },
  // 获取全部的咨询师擅长领域
  getExpertis: function () {
    wx.request({
      url: `${BASE_URL}/expertiseAreas`,
      success: (res) => {

        this.setData({
          list: res.data.data
        })
      }
    })
  },

  // 获取咨询师id的留言
  getMessage: function (id) {
    wx.request({
      url: `${BASE_URL}/consultMessage/consultId/${id}`,
      success: (res) => {
        this.setData({
          message: res.data.data
        })
        console.log(this.data.message);
      }
    })
  },

  // 获取咨询师的收费
  getCharges: function (id) {
    wx.request({
      url: `${BASE_URL}/consultCharges/consultId/${id}`,
      success: (res) => {
        this.setData({
          charges: res.data.data
        })
        console.log("charges", this.data.charges);
      }
    })
  },

  // 获取全部的咨询师评价
  getEvaluate: function (id) {
    wx.request({
      url: `${BASE_URL}/consultEvaluate/consultId/${id}`,
      success: (res) => {
        this.setData({
          evaluate: res.data.data
        })
        console.log(this.data.evaluate);
      }
    })
  },
  toConsult(e) {
    if(wx.getStorageSync('userInfo').id == null){
      wx.showToast({
        title: '请登录',
        icon:'error'
      })
      wx.reLaunch({
        url: "/pages/login/login",
      });
    }
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/consult/pages/ConsultSelectOrder/ConsultSelectOrder?id=' + id,
    })
  },
  // 查看更多 留言
  toMessage(e) {
    var id = e.currentTarget.dataset.id
    console.log(id);
    wx.navigateTo({
      url: '/consult/pages/ConsultMessage/ConsultMessage?id=' + id,
    })
  },

  // 查看更多 评价
  goHotArticlePage(e) {
    var id = e.currentTarget.dataset.id
    console.log("id====", id);
    wx.navigateTo({
      url: '/consult/pages/consultEvaluateMore/consultEvaluateMore?id=' + id,
    })
  },


  // 显示弹出层
  showInputModal: function () {
    this.setData({
      isModalVisible: true,
      isModalVisibleAsk:false
    });
  },

  // 隐藏弹出层
  hideInputModal: function () {
    this.setData({
      isModalVisible: false,
      inputValue: '',
      selectedValue: '5'
    });
  },

  // 输入框内容变化时触发
  onInput: function (event) {
    this.setData({
      inputValue: event.detail.value
    });
  },

  // 下拉框选择变化时触发
  onPickerChange: function (event) {
    const selectedValue = this.data.range[event.detail.value];
    this.setData({
      selectedValue: selectedValue
    });
  },

  // 确认输入
  confirmInput: function () {
    const inputValue = this.data.inputValue;
    const selectedValue = this.data.selectedValue;
    console.log('输入的内容:', inputValue);
    console.log('选择的值:', selectedValue);

    // 在这里处理确认逻辑
    if (inputValue == null || inputValue == '' || selectedValue == null || selectedValue == '') {
      wx.showToast({
        title: '请填写完整',
        icon: 'error'
      });
      return;
    }

    // 例如，保存输入的内容或执行其他操作
    let userid = '';
    const consultid = this.data.id;
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo == null || userInfo.id == null) {
      wx.showToast({
        title: "请登录",
        icon: 'error'
      });
      wx.switchTab({
        url: "/pages/login/login",
      });
    } else {
      userid = userInfo.id;
    }

    const entity = {
      userid: userid,
      consultid: consultid,
      score: selectedValue,
      content: inputValue
    };
    console.log('发送请求:', entity);

    wx.request({
      url: `${BASE_URL}/consultEvaluate`,
      method: "POST",
      data: entity,
      header: {
        'content-type': 'application/json' // 确保设置为 JSON
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });
          wx.redirectTo({
            url: '/consult/pages/consultDetail/consultDetail?id=' + consultid
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '请求失败，请重试',
          icon: 'error'
        });
      }
    });

    // 隐藏弹出层
    this.hideInputModal();
  },

  // 给咨询师 留言
  toAsk(){
    if(wx.getStorageSync('userInfo').id == null){
      wx.showToast({
        title: '请登录',
        icon:'error'
      })
      wx.reLaunch({
        url: "/pages/login/login",
      });
    }
    this.setData({
      isModalVisibleAsk:true,
      isModalVisible:false
    })
  },
  // 提交留言
  submitInputAsk(){
    const inputAsk = this.data.inputValueAsk
    if(inputAsk==''||inputAsk==null){
      wx.showToast({
        title: '请填写留言',
        icon:'error'
      })
      return 
    }
    let userid = '';
    const consultid = this.data.id;
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo == null || userInfo.id == null) {
      wx.showToast({
        title: "请登录",
        icon: 'error'
      });
      wx.switchTab({
        url: "/pages/login/login",
      });
    } else {
      userid = userInfo.id;
    }
    const entity = {
      content:inputAsk,
      userid:userid,
      consultid:consultid,
      reply:'无'
    }
    wx.request({
      url: `${BASE_URL}/consultMessage`,
      method:'POST',
      data: entity,
      header: {
        'content-type': 'application/json' // 确保设置为 JSON
      },
      success:(res)=>{
        if(res.data.code==200){
          wx.showToast({
            title: '提交成功',
          })
          wx.redirectTo({
            url: '/consult/pages/consultDetail/consultDetail?id=' + consultid
          });

        }
      },
    })


  },

  hideInputModalAsk: function() {
    this.setData({
      isModalVisibleAsk: false, // 隐藏留言弹出层
      inputValueAsk:''
    });
  },
    // 输入框内容变化时触发
    onInputAsk: function (event) {
      this.setData({
        inputValueAsk: event.detail.value
      });
    },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('页面参数:', options);
    this.setData({
      id: options.id || '',
    });
    this.fetchCourseDetail(options.id);
    this.getExpertis(options.id);
    this.getConsultExpertis(options.id)
    this.getCharges(options.id)
    this.getMessage(options.id)
    this.getEvaluate(options.id)
    if (options.source != null) {
      // console.log("通过订单进入");
      this.setData({
        isOrder: true
      })
    }
  },

  onPullDownRefresh: function () {
    console.log('开始下拉刷新');
    const id = this.data.id;
    if (!id) {
      wx.showToast({
        title: '无ID',
        icon: 'none'
      });
      wx.stopPullDownRefresh(); // 停止刷新动画
      return;
    }

    // 重新加载数据
    this.fetchCourseDetail(id);
    this.getExpertis(id);
    this.getConsultExpertis(id);
    this.getCharges(id);
    this.getMessage(id);
    this.getEvaluate(id);

    // 数据加载完成后停止刷新动画
    wx.stopPullDownRefresh();
  },
})